# -*- coding: utf-8 -*-
import os, Logger, shutil, hashlib, time, subprocess
import platform, re
import zipfile


def ExecCmd(cmd):
    Logger.INFO(cmd)
    ret = os.popen(cmd)
    print ret.read()


def ExecCmdWithSubProc(cmd):
    Logger.INFO(cmd)
    ret = subprocess.check_call(cmd, shell=True)
    print ret


def ExecCmdWithSubProcParallel(cmd):
    Logger.INFO(cmd)
    ret = subprocess.Popen(cmd, shell=True)
    print ret
    return ret


def copyFile(srcFile, destFolder):
    try:
        Logger.INFO("copy File: " + srcFile + " to " + destFolder)
        shutil.copy(srcFile, destFolder)
    except Exception as ex:
        Logger.ERROR("Copy File failed:")
        print ex
        exit(1)


def makedirs(path_dir):
    Logger.INFO("创建文件夹：" + path_dir)
    if os.path.exists(path_dir) != True:
        os.makedirs(path_dir)
    else:
        Logger.INFO("文件夹" + path_dir + "已经存在，不需要创建")


def CopyFolder(srcFolder, destFolder):
    Logger.INFO("Copying file from :" + srcFolder + " to: " + destFolder)
    '''
    Add copy folder code for different platform
    '''
    if platform.system() == "Windows":
        print "Platform: Windows\r\n"
        srcFolder = srcFolder.replace("/", "\\")
        destFolder = destFolder.replace("/", "\\")
        subprocess.call("xcopy %s %s /E /Y /C" % (srcFolder, destFolder), shell=True)
    elif platform.system() == "Linux":
        print "Platform: Linux\r\n"
        subprocess.call("cp -R %s %s" % (srcFolder + "/*", destFolder), shell=True)
    else:
        print "Platform: Unknown platform: %s\r\n" % (platform.system())
        exit(1)


def DelFolder(srcFolder):
    Logger.INFO("Deleting Dir: " + srcFolder)
    try:
        if os.path.isdir(srcFolder):
            shutil.rmtree(srcFolder)
    except Exception as err:
        print("remove folder error:" + str(err))


def DelFile(path_file):
    Logger.INFO("Deleting File: " + path_file)
    try:
        os.remove(path_file)
    except Exception as err:
        print("remove file error:" + str(err))


def chkPathExist(targetPath):
    if targetPath == "":
        Logger.ERROR("targetPath is empty!!!")
        exit(1)
    if os.path.exists(targetPath) != True:
        Logger.ERROR("targetPath not exists!!! " + targetPath)
        exit(1)


# warning when array size = 0
def chkArrSize(array):
    if len(array) == 0:
        Logger.WARNING("Array size = 0")
        return False
    return True


# error when array size = 0 and exit the program
def chkArrSizeFail(array):
    if len(array) == 0:
        Logger.ERROR("Array size = 0")
        exit(0)


def cleanUpGens(WORKSPACE, folders):
    Logger.INFO("Clean up: " + WORKSPACE)
    print folders
    if len(folders) != 0:
        for folder in folders:
            try:
                Logger.INFO("Clean up: " + folder)
                if os.path.exists(WORKSPACE + folder):
                    shutil.rmtree(WORKSPACE + folder)
            except Exception as ex:
                Logger.ERROR("cleanUpGens failed")
                print ex


def getFileMD5(pathToFile):
    ret = ""
    if os.path.exists(pathToFile) != True:
        Logger.WARNING("getFileMD5: File not exists: " + pathToFile)
    elif os.path.isfile(pathToFile) != True:
        Logger.WARNING("getFileMD5: PathToFile is not a file: " + pathToFile)
    else:
        md = hashlib.md5()
        fi = open(pathToFile, "rb")
        size = os.path.getsize(pathToFile)
        ti = time.time()
        try:
            while True:
                by = fi.read(8096)
                if not by:
                    break
                else:
                    md.update(by)
            ret = md.hexdigest().upper()
            ti = time.time() - ti
            Logger.INFO(("getFileMD5: total cost: %s sec, file size %f" % (ti, size)))
        except Exception as ex:
            Logger.ERROR("getFileMD5: Read file failed!")
            print ex
        finally:
            fi.close()
    return ret


def ReplaceFileContent(filename, srctext, dsttext):
    '''替换文件中的内容'''
    file = open(filename, "r")
    lines = file.readlines()
    ret = ""
    for line in lines:
        if line.find(srctext) != -1:
            print "Find Text:" + srctext
            line = line.replace(srctext, dsttext)
        ret = ret + line
    file.close()

    new_file = open(filename, "w")
    new_file.writelines(ret)
    new_file.close()


def searchString(text, pattern):
    """ test: 被搜索的源字符串
        pattern: 正则表达式语法
        index: 要获取的分组结果索引
    """
    m = re.search(pattern, text)
    if m:
        return m.group(0)


def findInFile(path_file, pattern):
    """ path_file: 文件路径
        pattern: 正则表达式语法
    """
    ret = False
    file = open(path_file, "r")
    lines = file.readlines()
    for line in lines:
        findstr = searchString(line, pattern)
        if findstr:
            ret = True
            break
    file.close()
    return ret


def zip_dir(dirname, zipfilename):
    Logger.INFO("压缩文件夹:" + zipfilename)
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else:
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))

    zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(dirname):]
        # print arcname
        zf.write(tar, arcname)
    zf.close()


def unzip_file(zipfilename, unziptodir):
    Logger.INFO("解压文件:" + unziptodir)
    if not os.path.exists(unziptodir):
        os.mkdir(unziptodir, 0777)
    zfobj = zipfile.ZipFile(zipfilename)
    for name in zfobj.namelist():
        name = name.replace('\\', '/')
        if name.endswith('/'):
            os.mkdir(os.path.join(unziptodir, name))
        else:
            ext_filename = os.path.join(unziptodir, name)
            ext_dir = os.path.dirname(ext_filename)
            if not os.path.exists(ext_dir):
                os.mkdir(ext_dir, 0777)
            outfile = open(ext_filename, 'wb')
            outfile.write(zfobj.read(name))
            outfile.close()


def changeChannel(path_file_sourceid, channel_id):
    """
    对渠道号文件进行修改
    """
    try:
        sourceidFile = './META-INF/sourceid.dat'
        file_sourceid = open(sourceidFile, "w")
        file_sourceid.writelines(channel_id)
        file_sourceid.close()
    except IOError as err:
        print("File Error:" + str(err))
        return False
    return True

def writrChannel(path_file_sourceid, channel_id):
    """
    对渠道号文件进行修改
    """
    try:
        sourceFile ='./'+'jdb/jDB-release-221_f4b6d1ad.apk/assets/sourceid.dat'
        print 'sourcefile',sourceFile
        print 'channelid',channel_id
        file_sourceid = open(sourceFile, "wr+")
        file_sourceid.writelines(channel_id)
        file_sourceid.close()
    except IOError as err:
        print("File Error:" + str(err))
        return False
    return True